﻿using System;
using Localization;
using SinBiota.Model.Business.AuthenticationServices;
using SinBiota.Model.Business.AuthenticationServices.Interfaces;
using SinBiota.Model.Business.PersistenceServices.Interfaces;
using SinBiota.Model.Business.ProjectServices.Interfaces;
using SinBiota.Model.Entities;
using SinBiota.Model.Exceptions;

namespace SinBiota.Model.Business.ProjectServices.Implementation
{
    public class ProjectManagement : IProjectManagement
    {
        private readonly IPermissionServices _permissionServices;
        private readonly IUserPersistenceServices _userPersistenceServices;

        public ProjectManagement(IPermissionServices permissionServices, IUserPersistenceServices userPersistenceServices)
        {
            _permissionServices = permissionServices;
            _userPersistenceServices = userPersistenceServices;
        }

        public void AddProjectMember(User requestingUser, Project project, User member)
        {
            // Permission:
            if (!_permissionServices.CanAddProjectMember(project, requestingUser))
            {
                throw new InvalidOperationException(Strings.NonAuthorized);
            }
            // Check if user already exists:
            if (project.Members.Contains(member)) 
                throw new InvalidOperationException(Messages.UserAlreadyIsProjectMember);
            if (project.Coordinators.Contains(member))
                throw new InvalidOperationException(Messages.UserAlreadyIsProjectCoordinator);
            // Add user and update :
            member.MemberProjects.Add(project);
            _userPersistenceServices.Update(member);

            return;
        }

        public void AddProjectCoordinator(User requestingUser, Project project, User coordinator)
        {
            // Permission:
            if (!_permissionServices.CanAddProjectCoordinator(project, requestingUser))
            {
                throw new InvalidOperationException(Strings.NonAuthorized);
            }
            // Check if user already exists:
            if (project.Members.Contains(coordinator))
                throw new InvalidOperationException(Messages.UserAlreadyIsProjectMember);
            if (project.Coordinators.Contains(coordinator))
                throw new InvalidOperationException(Messages.UserAlreadyIsProjectCoordinator);
            // Add user and update:
            coordinator.CoordinatorProjects.Add(project);
            _userPersistenceServices.Update(coordinator);
            return;

        }
    }
}